using System;
using System.Windows;
using System.Windows.Controls;

namespace TFS.Kanban.Commons.Controls
{
    // care of: http://blog.rag.no/post/A-simpler-(and-dynamic)-Grid-control-for-WPF.aspx
    public class DynamicGrid : Grid
    {
        public static readonly DependencyProperty NumColumnsProperty =
                    DependencyProperty.Register("NumColumns", typeof(Int32), typeof(DynamicGrid));

        public Int32 NumColumns
        {
            get { return (Int32)GetValue(NumColumnsProperty); }
            set { SetValue(NumColumnsProperty, value); }
        }


        public static readonly DependencyProperty NumRowsProperty =
                    DependencyProperty.Register("NumRows", typeof(Int32), typeof(DynamicGrid));

        public Int32 NumRows
        {
            get { return (Int32)GetValue(NumRowsProperty); }
            set { SetValue(NumRowsProperty, value); }
        }

        public static readonly DependencyProperty GridUnitTypeProperty =
            DependencyProperty.Register("GridUnitType", typeof (GridUnitType), typeof (DynamicGrid),
                                        new PropertyMetadata(GridUnitType.Star));

        public GridUnitType GridUnitType
        {
            get { return (GridUnitType) GetValue(GridUnitTypeProperty); }
            set { SetValue(GridUnitTypeProperty, value); }
        }

        private void RecreateGridCells()
        {
            var numRows = NumRows;
            var currentNumRows = RowDefinitions.Count;

            while (numRows > currentNumRows)
            {
                RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, this.GridUnitType) });
                currentNumRows++;
            }

            while (numRows < currentNumRows)
            {
                currentNumRows--;
                RowDefinitions.RemoveAt(currentNumRows);
            }

            var numCols = NumColumns;
            var currentNumCols = ColumnDefinitions.Count;

            while (numCols > currentNumCols)
            {
                ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, this.GridUnitType) });
                currentNumCols++;
            }

            while (numCols < currentNumCols)
            {
                currentNumCols--;
                ColumnDefinitions.RemoveAt(currentNumCols);
            }

            UpdateLayout();
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            RecreateGridCells();
        }
    }
}
